//
//  SCM3U8Analyse.m
//  VideoDownloadDemo
//
//  Created by 王琦 on 15/10/19.
//  Copyright (c) 2015年 Riverrun. All rights reserved.
//

#import "SCM3U8Analyse.h"
#import "SCM3U8SegmentList.h"
#import "Reachability.h"

@implementation SCM3U8Analyse

- (void)analyseVideoUrl:(NSString *)videoUrl VideoID:(NSString*)VideoID
{
    // http://pl.youku.com/playlist/m3u8?ts=1445566311&keyframe=1&vid=341551318&type=mp4&sid=34455663119462140827f&token=6551&oip=978552820&ep=DpN0VMkpPYjlR%2F8Nh8arIkJ%2F%2FBcjagpnLVQBetWjIgzaseyDkgFxrS5MPG3CO5jJ&did=65c906c26a8703f45f2f64b92bff8203e8697e75&ctype=21&ev=1
    // http://v.dezhi.com/content/m3u8/59dec18aace1f.m3u8
    NSLog(@"url====%@",videoUrl);
    NSRange rangeOfM3U8 = [videoUrl rangeOfString:@"m3u8"];
    if(rangeOfM3U8.location == NSNotFound){
        if(self.delegate && [self.delegate respondsToSelector:@selector(M3U8AnalyseFail:)]){
            NSError *err = [NSError errorWithDomain:videoUrl code:M3U8AnalyseFailNotM3U8Url userInfo:nil];
            [self.delegate M3U8AnalyseFail:err];
        }
        return;
    }
    
    NSURL *url = [NSURL URLWithString:videoUrl];
    NSError *error = nil;
    NSStringEncoding encoding;
    NSString *data = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];
    if(!data){
        if(self.delegate && [self.delegate respondsToSelector:@selector(M3U8AnalyseFail:)]){
            NSError *err = [NSError errorWithDomain:videoUrl code:M3U8AnalyseFailNetworkUnConnection userInfo:nil];
            [self.delegate M3U8AnalyseFail:err];
        }
        return;
    }
    
    
    NSString *remainData = data;
    //    NSLog(@"original data is %@",data);
    
    NSRange httpRange = [remainData rangeOfString:@"http"];
    if(httpRange.location == NSNotFound){
        //暂时只针对腾讯视频
        NSString *newString = @"av";
        NSRange range = [videoUrl rangeOfString:@"playlist.av.m3u8"];
        if(range.location != NSNotFound){
            newString = [NSString stringWithFormat:@"%@%@",[videoUrl substringToIndex:range.location],@"av"];
        }
        remainData = [remainData stringByReplacingOccurrencesOfString:@"av" withString:newString];
    }
    
    NSMutableArray *segments = [NSMutableArray array];
    NSRange segmentRange = [remainData rangeOfString:@"#EXTINF:"];
    NSInteger segmentIndex = 0;
    NSInteger totalSeconds = 0;
    
    NSString *regulaStr = @"\\bhttp?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
    NSError *errorr = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&errorr];
    NSArray *arrayOfAllMatches = [regex matchesInString:remainData options:0 range:NSMakeRange(0, [remainData length])];
    for (NSInteger i = 0; i<arrayOfAllMatches.count; i++){
        NSTextCheckingResult *match = arrayOfAllMatches[i];
        NSString* substringForMatch = [remainData substringWithRange:match.range];
        NSArray *nameArr = [substringForMatch componentsSeparatedByString:@"/"];
        NSString *fileName = nameArr.lastObject;
        SCM3U8SegmentInfo *segment = [[SCM3U8SegmentInfo alloc] init];
        NSRange commaRange = [remainData rangeOfString:@","];
        NSString *value = [remainData substringWithRange:NSMakeRange(segmentRange.location + [@"#EXTINF:" length], commaRange.location -(segmentRange.location + [@"#EXTINF:" length]))];
        segment.duration = [value intValue];
        segment.url = substringForMatch;
        segment.fileName = fileName;
        totalSeconds+=segment.duration;
        segment.index = segmentIndex;
        //
        segmentIndex++;
        [segments addObject:segment];
    }
    SCM3U8SegmentList *segmentList = [[SCM3U8SegmentList alloc] initWithSegments:segments];
    self.segmentList = segmentList;
    self.totalSeconds = totalSeconds;
    NSLog(@"片段url：%ld",segments.count);
    //解析完成后 直接写入本地
    NSString *pathPrefix = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *saveTo = [[pathPrefix stringByAppendingPathComponent:kPathDownload] stringByAppendingPathComponent:VideoID];
    
    NSLog(@"++++++++++%@",VideoID);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    NSError *err;
    [fileManager createDirectoryAtPath:saveTo withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *fullPath = [saveTo stringByAppendingPathComponent:@"movie.m3u8"];
    [remainData writeToFile:fullPath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    NSLog(@"视频路径:%@",fullPath);
    if(self.delegate && [self.delegate respondsToSelector:@selector(M3U8AnalyseFinish)]){
        [self.delegate M3U8AnalyseFinish];
    }
    
}

/* m3u8文件格式示例
 
 #EXTM3U
 #EXT-X-TARGETDURATION:30
 #EXT-X-VERSION:2
 #EXT-X-DISCONTINUITY
 #EXTINF:10,
 http://f.youku.com/player/getMpegtsPath/st/flv/fileid/03000201004F4BC6AFD0C202E26EEEB41666A0-C93C-D6C9-9FFA-33424A776707/ipad0_0.ts?KM=14eb49fe4969126c6&start=0&end=10&ts=10&html5=1&seg_no=0&seg_time=0
 #EXTINF:20,
 http://f.youku.com/player/getMpegtsPath/st/flv/fileid/03000201004F4BC6AFD0C202E26EEEB41666A0-C93C-D6C9-9FFA-33424A776707/ipad0_1.ts?KM=14eb49fe4969126c6&start=10&end=30&ts=20&html5=1&seg_no=1&seg_time=0
 #EXTINF:20,
 http://f.youku.com/player/getMpegtsPath/st/flv/fileid/03000201004F4BC6AFD0C202E26EEEB41666A0-C93C-D6C9-9FFA-33424A776707/ipad0_2.ts?KM=14eb49fe4969126c6&start=30&end=50&ts=20&html5=1&seg_no=2&seg_time=0
 #EXTINF:20,
 http://f.youku.com/player/getMpegtsPath/st/flv/fileid/03000201004F4BC6AFD0C202E26EEEB41666A0-C93C-D6C9-9FFA-33424A776707/ipad0_3.ts?KM=14eb49fe4969126c6&start=50&end=70&ts=20&html5=1&seg_no=3&seg_time=0
 #EXTINF:24,
 http://f.youku.com/player/getMpegtsPath/st/flv/fileid/03000201004F4BC6AFD0C202E26EEEB41666A0-C93C-D6C9-9FFA-33424A776707/ipad0_4.ts?KM=14eb49fe4969126c6&start=70&end=98&ts=24&html5=1&seg_no=4&seg_time=0
 #EXT-X-ENDLIST
 */


@end




